/**********************************************************************************
Program:       Real-time Weather Report

License:       GNU/GPL version 3

File:          WeatherForecast.cs

Description:   http连接获取一个城市的天气预报

Author:        Guangyu Liu （lgy0417@gmail.com）

Environment:   .NET Framework v2.0 or later version

Usage/Example: README_chs.txt

Last Modified: 2010.08.23

***********************************************************************************/


using System;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.Diagnostics;


namespace WeatherInfo
{
	public class WeatherForecast
	{
		#region Member Declaration
		
		private string _cityID;
		private string[] _info;
		private int _index;             // _info中第一个有效信息（当天日期）的索引
		private bool _has6forecasts = true;
		
		#endregion
		
		#region Properties
		
		public string CityID
		{
			get { return _cityID; }
			set {
				_cityID = value;
				GetForecastData();
			}
		}
		
		public bool Has6Forecasts
		{
			get { return _has6forecasts; }
		}
		
		public string[] ForecastInfo
		{
			get { return _info; }
		}
		
		public int ForecastInfoIndex
		{
			get { return _index; }
		}
		
		#endregion

		
		#region Fetch Data
		
		private void GetForecastData()
		{
			try
			{
				HttpWebRequest wrGETURL = (HttpWebRequest)WebRequest.Create("http://www.weather.com.cn/html/weather/" + _cityID + ".shtml");
				wrGETURL.UserAgent = "Mozilla/4.0(compatible;MSIE 6.0;Windows NT 5.0; .NET CLR 1.1.4322)";
				
				using(Stream objStream = wrGETURL.GetResponse().GetResponseStream())//;
				{
					StreamReader htmlReader = new StreamReader(objStream, System.Text.Encoding.GetEncoding("utf-8"));
					string htmlContent = "";
					for (int i = 1, j = 0; i < 960; i++)
					{
						htmlContent = htmlReader.ReadLine().Trim();
						if (i < 120 || htmlContent.Length == 0)           // 无有效信息
							continue;
						string htmlContent_Shortened = Regex.Replace(htmlContent, "<[^>]*>", "").Trim();   // 正则替换掉HTML标签
						if(htmlContent_Shortened.Length == 0)
							continue;
						if ((htmlContent_Shortened == "-->" && i > 900) || j > _info.Length - 1)     // “-->” 标志所有有效信息已结束
							break;
						_info[j] = Regex.Replace(htmlContent_Shortened, "&nbsp;", "");
						j++;
					}
				}
				for (_index = 0; _index < _info.Length; _index++)
					if (_info[_index][0] == '今')
						break;
				if (_info[_index + 26] == "夜间")
					_has6forecasts = false;
			}
			catch (System.Net.WebException we)
			{
				throw we;
			}
			catch (Exception e)
			{
				throw e;
			}
		}
		
		#endregion

		#region Constructor

		public WeatherForecast()
		{
			_info = new string[220];
		}

		#endregion
		
		// public void ConsoleDisplay()
		// {
			// Console.WriteLine(_info[_index]);
			// Console.WriteLine(_info[_index + 6] + "  " + _info[_index + 7] + "  " 
							// + _info[_index + 9]);                                           // 今日日出日落
			// Console.WriteLine(_info[_index + 10] + "  " + _info[_index + 11] + "  " 
							// + _info[_index + 13]);                                          // 明日日出日落 
			// Console.WriteLine("\n" + _info[_index + 16] + " " + _info[_index + 17]);    // 天气预报发布时间
			// if(_has6forecasts == false)
			// {
				// Console.WriteLine("\n" + _info[_index + 25]);                 // 先输出当天夜间预报
				// Console.WriteLine(_info[_index + 26] + "  " + _info[_index + 27] + "  "
								// + _info[_index + 28] + "  " + _info[_index + 29] + "  "
								// + _info[_index + 30]);
			// }
			// int _indexOfForecasts = _has6forecasts ? _index + 25 : _index + 31;
			// for(int i = _indexOfForecasts; i < 109; i += 11)
			// {
				// if(i == _indexOfForecasts + 33)
					// Console.WriteLine("\n" + _info[i++]);
				// if(i == _indexOfForecasts + 67)
				// {
						// Console.WriteLine("\n" + _info[i]);                   // 只剩下半天
						// Console.WriteLine(_info[i + 1] + "  " + _info[i + 2] + "  " 
										// + _info[i + 3] + "  " + _info[i + 4] + "  " 
										// + _info[i + 5]);
						// break;
				// }
				// Console.WriteLine("\n" + _info[i]);                                   // 日期
				// Console.WriteLine(_info[i + 1] + "  " + _info[i + 2] + "  " 
								// + _info[i + 3] + "  " + _info[i + 4] + "  " 
								// + _info[i + 5]);                                      // 白天预报
				// Console.WriteLine(_info[i + 6] + "  " + _info[i + 7] + "  " 
								// + _info[i + 8] + "  " + _info[i + 9] + "  " 
								// + _info[i + 10]);                                     // 夜间预报
			// }
		// }
		
		/* Method Main() for testing Class WeatherForecast */
		// public static void Main()
		// {
			// Console.Write("Fetching and analyzing data from Web......");
			// DateTime p = DateTime.Now;
			// WeatherForecast wf = new WeatherForecast();
			// wf.CityID = "101010100";
			// Console.WriteLine("Done!\n");
			// wf.ConsoleDisplay();
			// DateTime n = DateTime.Now;
			// Console.WriteLine("\nTime Elapsed: {0} ms", n.Subtract(p).TotalMilliseconds);
		// }
	}
}
